package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import modelo.Contato;


public class DAOContato {
	
	 private Connection conexao;
	 
	 private void obterConexao(){
	        try {
	            Class.forName("com.mysql.jdbc.Driver");
	            conexao = DriverManager.getConnection("jdbc:mysql://localhost/sirp", "root", "123");
	        } catch (ClassNotFoundException e) {
	            e.printStackTrace();
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	    }
	    
	    private void liberarConexao(){
	        try {
	            conexao.close();
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	    }    
	    	
	     public void inserir(Contato contato){
	        obterConexao();
	        try {
	            PreparedStatement pstat = conexao.prepareStatement("INSERT INTO Contato (codigo) VALUES (?)");
	            pstat.setInt(1, contato.getId());
	            pstat.setInt(2, contato.getCodigo());
	            
	        } catch (SQLException e) {
	            e.printStackTrace();
	        }
	        liberarConexao();
	    }
	     
	     public void excluir(Contato contato){
	    	 obterConexao();
		        try {
		            Statement stat = conexao.createStatement();
		            stat.executeUpdate("DELETE FROM Contato WHERE codigo = '" + contato.getCodigo() + "' ");
		        } catch (SQLException e) {
		            e.printStackTrace();
		        }
		        liberarConexao();
	    	 
	     }
	     public Contato buscarContato(int codigo){
	    	 obterConexao();
	    	 try{
	    		 PreparedStatement pstat= conexao.prepareStatement("SELECT * FROM Contato WHERE codigo=?");
	    		 pstat.setInt(1, codigo);
	    		 ResultSet set = pstat.executeQuery();
	    		 
	    		 if (set.next()){
		            	Contato contato= new Contato();
		            	contato.setId(set.getInt("id"));
		            	contato.setCodigo(set.getInt("codigo"));
		                set = pstat.executeQuery();
		                
		                pstat = conexao.prepareStatement("SELECT count(*) FROM Contato WHERE codigo = ?");
		                pstat.setInt(1, codigo);
		                set = pstat.executeQuery();
		                
		                return contato;
		               
	    		 }
	    		 
	    	 }catch(SQLException e){
	    		 e.printStackTrace();
	    	 }
			return null;
	     }

}
